package com.musicserver.controller;

import com.musicserver.common.JwtUtils;
import com.musicserver.common.R;
import com.musicserver.common.Token;
import com.musicserver.model.domain.Consumer;
import com.musicserver.model.request.ConsumerRequest;
import com.musicserver.service.ConsumerService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class ConsumerController {

    @Autowired
    private ConsumerService consumerService;
    /**
     *管理界面调用：返回所有用户
     */
    @GetMapping("/user")
    public R allUser() {
        return consumerService.allUser();
    }
    /**
     * 分页查询所有用户
     * @param currentPage 当前页码
     * @param pageSize 每页大小
     * @return 分页用户数据
     */
    @GetMapping("/users")
    public R users(@RequestParam(defaultValue = "1") Integer currentPage,
                   @RequestParam(defaultValue = "10") Integer pageSize) {
        return consumerService.allUser(currentPage, pageSize);
    }

    /**
     *删除用户
     */
    @GetMapping("/user/delete")
    public R deleteUser(@RequestParam int id) {
        return consumerService.deleteUser(id);
    }

    /**
     *批量删除用户
     */
    @DeleteMapping("/user/deleteIds")
    public R deleteUsers(@RequestParam String[] id){
        return consumerService.deleteUsers(id);
    }

    @GetMapping("/user/detail")
    public R userOfId(@RequestParam int id) {
        return consumerService.userOfId(id);
    }

    @PostMapping("/user/login/status")
    public R loginStatus(@RequestBody ConsumerRequest loginRequest, HttpSession session) {
        R result = consumerService.loginStatus(loginRequest, session);
        //登录成功的话，返回中需要包含token信息
        if(result.getSuccess()){
            String tokenStr = JwtUtils.generateToken(loginRequest.getUsername());
            Token<Object> token = new Token<>();
            token.setAuthorization(tokenStr);
            token.setObj(result.getData());
            result.setData(token);
        }
        return result;
    }

    @PostMapping("/user/add")
    public R addUser(@RequestBody ConsumerRequest registryRequest) {
        return consumerService.addUser(registryRequest);
    }

    @PostMapping("/user/update")
    public R updateUserMsg(@RequestBody ConsumerRequest updateRequest) {
        return consumerService.updateUserMsg(updateRequest);
    }
    @PostMapping("/user/avatar/update")
    public R updateUserPic(@RequestParam("file") MultipartFile avatorFile,
                           @RequestParam("id") int id) {
        return consumerService.updateUserAvator(avatorFile, id);
    }
    @PostMapping("/user/updatePassword")
    public R updatePassword(@RequestBody ConsumerRequest updatePasswordRequest) {
        return consumerService.updatePassword(updatePasswordRequest);
    }

}
